package com.ideal.manage.esms.compoment;

import com.alibaba.fastjson.JSONObject;
import com.ideal.manage.esms.bean.alarm.Alarm;
import com.ideal.manage.esms.bean.alarm.QAlarm;
import com.ideal.manage.esms.bean.project.AlarmInfo;
import com.ideal.manage.esms.bean.project.EquipmentManage;
import com.ideal.manage.esms.jpa.JpaRepositoryImpl;
import com.ideal.manage.esms.repository.alarm.AlarmRepository;
import com.ideal.manage.esms.repository.project.EquipmentManageRepository;
import com.ideal.manage.esms.repository.project.ProjectManageRepository;
import com.ideal.manage.esms.service.ElasticsearchService;
import com.ideal.manage.esms.service.monitor.Utils;
import com.ideal.manage.esms.util.ElasticsearchUtils;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.scheduling.annotation.Scheduled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * Created By shenli On 2018/8/19
 * Remark: 5分钟运行生成一次告警数据
 */
@Component
@Lazy(false)
public class GetAlarmHitsComponent {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private EquipmentManageRepository equipmentManageRepository;

    @Autowired
    private ProjectManageRepository projectManageRepository;

    @Autowired
    private AlarmRepository alarmRepository;

    @Autowired
    private EntityManager entityManager;

    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchUtils.class);

    @PostConstruct
    public void init() {
        //this.alarmRepository = new JpaRepositoryImpl<Alarm, String>(Alarm.class, entityManager);
    }

    private  Map<String, String> mapCacheDay = new HashMap();

    /**
     * 5分钟运行生成一次告警数据
     */
    @Scheduled(fixedDelay = 300000)
    public void getAlarmHits() {
        //获取所有的项目的ip
        List<String> ips = projectManageRepository.findByPip();
        //报警过程找到适用对象(有效的设备)
        List<EquipmentManage> equipmentManageList = equipmentManageRepository.findAllEquipmentsCode(ips);
        //获取设备的唯一标识(code)

        //某项目-某电池包，只有电池包有告警
        for (EquipmentManage eq : equipmentManageList) {
            if (!"2".equals(eq.getEquipmentType()))
                continue;
            //目前只判断时间，5分钟范围内
            LocalDateTime localDateTime = LocalDateTime.now();
            Date startDate = Date.from(localDateTime.minusMinutes(5L).toInstant(ZoneOffset.of("+8")));
            Date endDate = Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));

            List<JSONObject> jsonObjects = elasticsearchService.searchByMatchFunction(QueryBuilders.boolQuery()
                    .filter(QueryBuilders.termQuery("ip", eq.getProject().getIp()))//"192.168.0.1"
                    .filter(QueryBuilders.termQuery("macid", eq.getCode())) //eq.getCode() 24
                    .filter(QueryBuilders.rangeQuery("time").gte(startDate.getTime()).lte(endDate.getTime()))
                    .filter(QueryBuilders.existsQuery("Alarm_BatUC")), name -> {
                return name.startsWith("Alarm_");
            });

            /**
             *
             * {
             *                     "Alarm_BatUC": 0,
             *                     "Alarm_BatDT": 0,
             *                     "Alarm_Bmuil": 0,
             *                     "macid": "24",
             *                     "Alarm_AuxFail": 0,
             *                     "Alarm_BatDV": 0,
             *                     "Alarm_BSU_OFFLINE": 0,
             *                     "Alarm_BatOC": 0,
             *                     "Alarm_BSU_FAULT": 0,
             *                     "date_time": "2018-08-18 11:38:25",
             *                     "Alarm_LBK": 0,
             *                     "id": "31085_c0add223c92e4a1aa0e1036548f16945",
             *                     "Alarm_TBK": 0,
             *                     "Alarm_Hall_Break": 0,
             *                     "Alarm_HV_Fail": 0,
             *                     "Alarm_CellUT": 0,
             *                     "ip": "192.168.0.1",
             *                     "Alarm_PrechrgFail": 0,
             *                     "messageId": "409288947",
             *                     "port": "4001",
             *                     "Alarm_LEAK_OC": 0,
             *                     "Alarm_BatOV": 0,
             *                     "time": 1534563505549,
             *                     "Alarm_CellUV": 0,
             *                     "Alarm_BatUV": 0,
             *                     "Alarm_CellOV": 0,
             *                     "Alarm_Vcu_Offline": 0,
             *                     "Alarm_CellOT": 0
             *                 }
             *
             * */
            //把所有告警的数据放到一个cache的map中，按天放,同一个告警每天只有一个
            for (JSONObject json : jsonObjects) {
                for (String key : json.keySet()) {
                    if(!key.startsWith("Alarm_"))
                        continue;
                    if(json.getIntValue(key) == 0)
                        continue;

                    if(mapCacheDay.get(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))+"#"+key+"#"+json.getIntValue(key)) == null){
                        mapCacheDay.put(LocalDateTime.now().format(DateTimeFormatter
                                        .ofPattern("yyyyMMdd"))+"#"+key+"#"+json.getIntValue(key),
                                LocalDateTime.now().toString());
                        List<AlarmInfo> alarmInfoList = alarmRepository.findAlarmInfoByLevandEsname(json.getIntValue(key),key);
                        if(alarmInfoList.size() > 0 ){
                            Alarm alarm = new Alarm();
                            alarm.setAlarmContent(alarmInfoList.get(0).getName());
                            alarm.setEquipmentName(eq.getName());
                            alarm.setSource("BMS");
                            int level = json.getIntValue(key);
                            if (level == 1) {
                                alarm.setDealIdea("建议关闭系统");
                            } else if (level == 2) {
                                alarm.setDealIdea("建议通知工程师处理");
                            } else if (level == 3) {
                                alarm.setDealIdea("建议现场处理");
                            } else if (level == 4) {
                                alarm.setDealIdea("建议跟踪观察");
                            } else {
                                alarm.setDealIdea("无法根据报警类容给出建议");
                            }
                            alarm.setAlarmLev(json.getString(key));
                            alarm.setEquipmentId(eq.getId());
                            alarm.setState(1);
                            alarm.setIsValid(1);
                            alarm.setCreateTime(new Date());
                            alarm.setOperateTime(new Date());
                            alarmRepository.save(alarm);
                        }else{
                            logger.info(" 告警字段: "+key+"  告警等级："+json.getIntValue(key)+"   没有设置过程报警");
                        }
                    }
                }
            }
        }
    }
}
